package com.example.demo.service;

import com.example.demo.dao.CommodityJPARepository;
import com.example.demo.entity.Commodity;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.Predicate;
import java.util.*;

@Service
public class CommodityService {

    @Autowired
    CommodityJPARepository commodityJPARepository;

    public Commodity addCommodity(Commodity commodity){
        return commodityJPARepository.saveAndFlush(commodity);
    }

    public Commodity getCommodity(long id) {
        return commodityJPARepository.getReferenceById(id);
    }

    public List<Commodity> findCommodity(String commodityName,String supplierName){
        Specification<Commodity> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if (commodityName != null) {
                predicateList.add(criteriaBuilder.like(root.get("name"), "%" + commodityName + "%"));
            }
            if(supplierName != null){
                predicateList.add(criteriaBuilder.like(root.join("suppliers").get("name"),"%" + supplierName + "%"));
            }
            Predicate[] predicates = predicateList.toArray(new Predicate[predicateList.size()]);
            return criteriaBuilder.and(predicates);
        };

        List<Commodity> result = commodityJPARepository.findAll(specification);
        return result;
    }

    public void updateCommodity(Commodity commodity){
        commodityJPARepository.save(commodity);
    }

    public void deleteCommodity(long id){commodityJPARepository.deleteById(id);}

    public void deleteAll(){
        commodityJPARepository.deleteAll();
    }

}
